import axios from "axios";
// import qs from 'qs'
import router from "@/router/index";
import {
  ElMessage,
  ElLoading,
  ElMessageBox,
  ElNotification,
} from "element-plus";
import { useStore } from "@/store/index"; //引入store
let loading = null;
let isShowLoading = false;
let requestCount = 0;
let index = 0;
const service = axios.create({
  timeout: 60000, //超时时间
  baseURL: "", // 接口地址 //import.meta.env.VITE_BASE_URL
  // transformRequest: data => qs.stringify(data)    //post 请求参数处理,防止 post 请求跨域
});

service.defaults.headers["Content-Type"] = "application/json";
// http request 拦截器
service.interceptors.request.use(
  (config) => {
    const store = useStore();
    config.headers["Authorization"] = store.token;
    if (isShowLoading && requestCount == 0) {
      loading = ElLoading.service({
        lock: true,
        text: isShowLoading,
        background: "rgba(0, 0, 0, 0.7)",
        target: document.querySelector("#main-home-content"), // 设置加载显示区域
      });
    }
    requestCount++;
    return config;
  },
  (err) => {
    return err;
  }
);
// http response 数据响应
service.interceptors.response.use(
  (response) => {
    const store = useStore();
    //接收返回数据..
    const res = response.data;
    const codeList = [403, 500, 50000, 40000];
    requestCount--;
    if (requestCount == 0 && loading) {
      loading.close();
    }

    // 判断返回数据是否存在状态 code 和错误提示信息..
    if (!res) {
      return showMessage("响应数据格式错误", "error");
    }

    if (codeList.includes(res.code)) {
      return showMessage(res.message);
    }
   
    if (res.code == 40020) {
      if (index == 0) {
        ElMessageBox.confirm(res.message, "登录过期", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          store.setToken('')
          router.replace(store.loginPath)
          index = 0;
        });
        index++;
      }
      return Promise.reject(res);
    }
    return res;
  },
  (err) => {
    requestCount--;
    if (requestCount == 0 && loading) {
      loading.close();
    }
    console.log(err);
    ElNotification({
      title: `服务器状态码: ${err.response.status}`,
      message: h("i", { style: "color: teal" }, err.message),
      position: "bottom-left",
      type: "error",
      duration: 5 * 1000,
    });
    return showMessage(err.response.data.message);
  }
);

//封装错误提示信息..
function showMessage(message, type = "error", showClose = true) {
  ElMessage({
    showClose, //是否显示 X
    message, //错误提示信息
    type, //显示类型
    duration: 3 * 1000, //展示时间
  });
  return Promise.reject(message);
}

const ajax = {
  // url 请求地址(必传)    params 请求参数(必传)  loading 是否显示loading(加载中动画  非必传)
  // get请求
  get(url, params, loading) {
    isShowLoading = loading;
    const config = {
      method: "get",
      url: url,
      params: params,
    };
    // if (params) config.params = params;
    return service(config);
  },
  // post请求
  post(url, params, loading) {
    isShowLoading = loading;
    const config = {
      method: "post",
      url: url,
      data: params,
    };
    // if (params) config.data = params;
    return service(config);
  },
  // put请求
  put(url, params, loading) {
    isShowLoading = loading;
    const config = {
      method: "put",
      url: url,
      data: params,
    };
    // if (params) config.data = params;
    return service(config);
  },
  // put请求
  putGet(url, params, loading) {
    isShowLoading = loading;
    const config = {
      method: "put",
      url: url,
      params: params,
    };
    // if (params) config.data = params;
    return service(config);
  },
  // delete请求
  delete(url, params, loading) {
    isShowLoading = loading;
    const config = {
      method: "delete",
      url: url,
      params: params,
    };
    // if (params) config.params = params;
    return service(config);
  },
};

export default ajax;
